<script setup>
	import {
		navigateBack,
		navigateToWishingTreeRecord,
		navigateToRecharge,
	} from "@/assets/scripts/navigate.js"
	import {
		likeApi,
		likeStatisticsApi,
		statisticsApi,
		getWishTreeUserListApi,
		getWishTreeListApi,
		postWishTreeUserApi,
	} from "@/assets/api/other/wishingTree.js"
	import {
		onMounted,
		ref
	} from 'vue';

	const userInfo = ref({})
	const likeStatisticsObj = ref({
		isLike: false,
		likeNum: 0,
	})
	const statisticsNum = ref(0)
	const infoPopup = ref()
	const showPopup = ref()
	const formPopup = ref()
	const isSelect = ref(false)
	const showRandomLabelFlag = ref(false)
	const formData = ref({
		remark: '',
		wtName: '',
		wishTreeIds: '',
		yuw: '',
		isAnonymous: '否'
	})
	const dataSource = ref({})
	const wishTreeList = ref([])

	const showRandomLabel = async (label) => {
		try {
			if (showRandomLabelFlag.value) {
				throw new Error('操作太频繁')
			}
			showRandomLabelFlag.value = true
			const res = await getWishTreeUserListApi('', label, '')
			if (res && Array.isArray(res.rows) && res.rows.length) {
				// 随机抽取一个
				const randomIndex = Math.floor(Math.random() * res.rows.length)
				dataSource.value = res.rows[randomIndex];
				await likeStatistics(dataSource.value.id);
				showPopup.value.open()
			} else throw new Error('暂无人许愿')
		} catch (e) {
			uni.showToast({
				title: e?.message || '查询失败',
				icon: "error"
			})
		} finally {
			setTimeout(() => {
				showRandomLabelFlag.value = false
			}, 1000)
		}
	}

	const handleAdd = () => {
		formData.value = {
			wishTreeIds: '',
			yuw: '',
			isAnonymous: '否'
		}
		formPopup.value.open()
	}

	const handleLike = async (item) => {
		try {
			const res = await likeApi(item.id)
			if (res && res.code === 200) {
				uni.showToast({
					title: item.id ? "祝福成功" : "操作成功",
					icon: 'success',
					success: () => {
						likeStatistics(item.id)
					}
				})
			} else throw new Error(res?.msg || '祝福失败');
		} catch (e) {
			uni.showToast({
				title: e?.message || '操作失败',
				icon: "error"
			})
		}
	}

	const handleSubmit = async () => {
		try {
			if (!(formData.value.wishTreeIds && formData.value.yuw)) {
				throw new Error('请填写许愿内容和选择许愿牌');
			}
			const res = await postWishTreeUserApi({
				...formData.value,
				userId: userInfo.value.userId
			});
			if (res && res.code === 200) {
				uni.showToast({
					title: "许愿成功",
					icon: 'success',
					success: () => {
						formPopup.value.close()
						statistics()
					}
				})
			} else if (res && res.code === 500) {
				uni.showModal({
					content: '余额不足请充值!是否跳转充值!',
					title: '温馨提示',
					success: (e) => {
						if (e.confirm) {
							formPopup.value.close()
							navigateToRecharge()
						}
					}
				})
			} else throw new Error(res?.msg || '许愿失败');
		} catch (e) {
			uni.showToast({
				title: e?.message || '操作失败',
				icon: "error"
			})
		}
	}

	const handleSwitchChange = (e) => {
		formData.value.isAnonymous = e.detail.value ? '是' : '否'
	}

	const list_init = async () => {
		try {
			const res = await getWishTreeListApi()
			if (res && Array.isArray(res.rows) && res.rows.length) {
				wishTreeList.value = res.rows
			} else throw new Error('')
		} catch (e) {
			uni.showToast({
				title: '请求标签失败',
				icon: 'error'
			})
		}
	}

	const statistics = async () => {
		try {
			const res = await statisticsApi()
			if (res) {
				statisticsNum.value = res.data
				console.log(res);
			} else throw new Error('')
		} catch (e) {
			uni.showToast({
				title: '统计失败',
				icon: 'error'
			})
		}

	}

	const likeStatistics = async (id) => {
		try {
			const res = await likeStatisticsApi(id)
			if (res && res.code === 200) {
				likeStatisticsObj.value = res.data
				console.log(res);
			} else throw new Error('')
		} catch (e) {
			uni.showToast({
				title: '统计失败',
				icon: 'error'
			})
		}

	}

	const handleLabelClick = (item) => {
		isSelect.value = false
		formData.value.wishTreeIds = item.id
		formData.value.remark = item.remark
		formData.value.wtName = item.wtName
	}

	onMounted(async () => {
		userInfo.value = uni.getStorageSync('user')
		await list_init()
		await statistics()
	})
</script>

<template>
	<view class="tree-page page-wrap">

		<uv-popup ref="showPopup" class="show-popup-parent" mode="top" customStyle="background: transparent;"
			style="background: transparent;" closeable>
			<view class="show-popup">
				<view class="show-box">
					<image src="@/assets/pic/wish-show.png" mode="widthFix" class="show-bg"></image>
					<view class="show-ab-box">
						<view class="wish-content">
							{{dataSource?.yuw}}
						</view>
						<view class="bottom-av-like">
							<view class="d-flex d-flex-aic d-flex-fx1">
								<uv-avatar :src="dataSource?.isAnonymous === '否' ? dataSource?.avatar : ''"
									shape="square" size="60rpx"></uv-avatar>
								<text
									class="ml-small text-ellipsis name">{{dataSource?.isAnonymous === '否'?dataSource?.userName:'匿名'}}</text>
							</view>
							<view class="d-flex d-flex-aic d-flex-fs0 like" @click='handleLike(dataSource)'>
								<uv-icon :name="!likeStatisticsObj.isLike?'heart':'heart-fill'" color="#fff"></uv-icon>
								<text>{{likeStatisticsObj.likeNum}}人祝福</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</uv-popup>

		<uv-popup ref="formPopup" closeable class="form-popup-parent" mode="top" customStyle="background: transparent;"
			style="background: transparent;">
			<view class="form-popup">
				<view class="form-box">
					<image src="@/assets/pic/wish-form.png" mode="widthFix" class="form-bg"></image>
					<view class="form-ab-box">
						<view class="form-title">
							每个许愿签需要消耗3缅怀币
						</view>
						<view class="form-tip">
							每个人心中都有美好的愿望，为自己、亲友诚心祝福，许下心愿，挂在祈福树上，愿望会早日实现哦！
						</view>
						<view class="form-select" @click='isSelect = !isSelect'>
							<text>选择许愿牌
								{{formData.wtName}}</text>
							<uv-icon :name="!isSelect?'arrow-down':'arrow-up'" color="#851717"></uv-icon>
						</view>
						<view class="form-content">
							<template v-if="!isSelect">
								<textarea v-model="formData.yuw" maxlength="200" class="form-inp"
									placeholder="请输入心中的愿望(200字以内)"></textarea>
							</template>
							<template v-else="isSelect">
								<view class="select-list">
									<view v-for="(item, index) in wishTreeList" :key="index"
										:class="['item', {active:formData.wishTreeIds.includes(item.id)}]"
										@click="handleLabelClick(item)">{{item.wtName}}</view>
								</view>
							</template>
							<view class="my-switch">
								匿名<switch class="ml-small" @change="handleSwitchChange"></switch>
							</view>
						</view>
						<view class="form-opts">
							<view class="btn" @click="handleSubmit">
								提交
							</view>
						</view>
					</view>
				</view>
			</view>
		</uv-popup>

		<uv-popup ref="infoPopup" mode="center" round='10' :safe-area-inset-bottom="false"
			customStyle="width: 90%;border: 4rpx solid #86201c;">
			<view class="info-popup">
				<view class="p-normal box">
					<view class="font-fs18 d-flex d-flex-jcc">
						许愿树使用说明
					</view>
					<view class="font-fs14 my-normal">
						每个人心中都有美好的愿望，为自己、亲友诚心祈福，许下心愿，挂在祈福树上，愿望会早日实现哟！
					</view>
					<view class="font-fs14 ">
						1.每使用一个许愿需要消耗6缅怀币。
					</view>
					<view class="font-fs14 ">
						2.点击许愿牌可以看到大家写的愿望，可为他人的愿望进行祝福。
					</view>
					<view class="font-fs14 ">
						3.点击“祈福”按钮，可以自由选择许愿牌类型，进行祈福许愿。
					</view>
					<view class="font-fs14 ">
						4.点击“我的祈福”可以查看自己的祈福愿望，并进行管理。
					</view>
				</view>
			</view>
		</uv-popup>

		<view class="tree-box page-wrap">
			<image src="@/assets/pic/tree.jpg" mode="aspectFill" class="tree-bg"></image>
		</view>

		<view class="label-list page-wrap">
			<image v-for="(item, index) in wishTreeList" :key="index" @click="showRandomLabel(item.id)"
				:src="item.remark" mode="widthFix" class="image image-fill-x item"></image>
			<image src="@/assets/pic/小福灯笼.gif" mode="widthFix" class="image image-fill-x light"></image>
			<image src="@/assets/pic/小福灯笼.gif" mode="widthFix" class="image image-fill-x light"></image>
			<image src="@/assets/pic/小福灯笼.gif" mode="widthFix" class="image image-fill-x light"></image>
		</view>

		<view class="d-flex d-flex-jcsb d-flex-aic top-title">
			<view class="d-flex-fs0 btn" @click="navigateBack">返回首页</view>
			<view class="tip">已有{{statisticsNum}}人祈福许愿</view>
			<view class="d-flex-fs0 d-flex btn" @click="infoPopup.open()"><uv-icon name="question-circle"
					color="#888888" class="mr-small"></uv-icon>说明</view>
		</view>

		<view class="d-flex d-flex-jcsb d-flex-aic bottom-btn page-wrap">
			<view class="d-flex-fx1 mr-big btn" @click="handleAdd">
				<image src="@/assets/pic/i-will-wish.gif" mode="widthFix" class="image image-fill-x"></image>
			</view>
			<view class="d-flex-fx1 btn" @click='navigateToWishingTreeRecord'>
				<image src="@/assets/pic/my-wish.gif" mode="widthFix" class="image image-fill-x"></image>
			</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.tree-page {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;

		::v-deep .form-popup-parent {
			[name='content'] {
				background-color: transparent !important;
			}

			.uv-popup__content__close {
				// background: #007aff;
				border-radius: 50%;
				padding: 10px;
				top: 50px;
				right: 10px;

				.uv-icon__icon {
					color: #fff !important;
				}
			}

			.form-popup {
				display: flex;
				justify-content: center;

				.form-box {
					width: 90%;
					position: relative;

					.form-bg {
						width: 100%;
					}

					.form-ab-box {
						position: absolute;
						top: 15%;
						left: 12%;
						right: 12%;
						bottom: 15%;
						overflow: hidden;
						padding: 10rpx;
					}

					.form-title {
						font-size: 28rpx;
						height: 48rpx;
						line-height: 48rpx;
					}

					.form-tip {
						display: -webkit-box;
						text-overflow: ellipsis;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 3;
						overflow: hidden;
						font-size: 24rpx;
						color: #851717;
						line-height: 42rpx;
						padding: 10rpx;
						// background-color: rgba(0,0,0,.3);

					}

					.form-select {
						margin-top: 14rpx;
						// background-color: rgba(0, 0, 0, .3);
						height: 54rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						padding: 0 20rpx;
						color: #851717;

						text {
							font-size: 28rpx;
						}
					}

					.form-opts {
						margin-top: 36rpx;
						display: flex;
						justify-content: center;

						.btn {
							height: 64rpx;
							width: 300rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							background-color: #f2502a;
							color: #fffffe;
							border-radius: 32rpx;
							box-shadow: -2px 3px 1px 0px #222222c2, -3px 3px 6px 0px #ffffffc9 inset;
							transition: all .3s;

							&:active {
								transform: scale(.9);
								opacity: .7;
							}
						}
					}

					.form-content {
						// background-color: rgba(0, 0, 0, .3);
						margin-top: 14rpx;

						.my-switch {
							font-size: 28rpx;
							margin-top: 15rpx;
							overflow: hidden;
						}

						.form-inp {
							// background-color: rgba(0, 0, 0, .3);
							height: 210rpx;
							box-sizing: border-box;
							padding: 15rpx;
							font-size: 28rpx;
						}

						.select-list {
							height: 210rpx;
							box-sizing: border-box;
							display: flex;
							padding: 12rpx;
							flex-wrap: wrap;

							.item {
								margin-bottom: 10rpx;
								margin-right: 10rpx;
								width: max-content;
								height: 48rpx;
								color: #851717;
								font-size: 24rpx;
								display: flex;
								align-items: center;
								padding: 0 16rpx;
								background-color: #fffffe;
								border-radius: 8rpx;

								&.active {
									background-color: #851717;
									color: #fffffe;
								}
							}

						}

					}


				}
			}
		}

		::v-deep .show-popup-parent {
			[name='content'] {
				background-color: transparent !important;
			}

			.uv-popup__content__close {
				// background: #007aff;
				border-radius: 50%;
				padding: 10px;
				top: 50px;
				right: 10px;

				.uv-icon__icon {
					color: #fff !important;
				}
			}

			.show-popup {
				display: flex;
				justify-content: center;

				.show-box {
					width: 80%;
					position: relative;

					.show-bg {
						width: 100%;
					}

					.show-ab-box {
						position: absolute;
						top: 20%;
						left: 20%;
						right: 20%;
						bottom: 34%;
						overflow: hidden;
						padding: 10rpx;
						// background-color: rgba(0, 0, 0, .3);
					}

					.wish-content {
						// background-color: rgba(0, 0, 0, .3);
						height: 420rpx;
					}

					.bottom-av-like {
						// background-color: rgba(0, 0, 0, .3);
						height: 60rpx;
						margin-top: 20rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.name {
							width: 100rpx;
						}

						.like {
							height: 40rpx;
							border-radius: 20rpx;
							background-color: #00a64f;
							color: #fff;
							font-size: 24rpx;
							padding: 0 12rpx;
							transition: all .3s;

							&:active {
								opacity: .7;
								transform: scale(.9);
							}
						}
					}


				}
			}
		}

		.info-popup {
			.box {}
		}

		.label-list {
			position: absolute;
			top: 140rpx;
			bottom: 0;
			left: 0;
			right: 0;

			.item {
				width: 60rpx;
				position: absolute;

				&:nth-of-type(1) {
					top: 0%;
					left: 50%;
				}

				&:nth-of-type(2) {
					top: 2%;
					left: 36%;
				}

				&:nth-of-type(3) {
					top: 8%;
					left: 24%;
				}

				&:nth-of-type(4) {
					top: 16%;
					left: 12%;
				}

				&:nth-of-type(5) {
					top: 19%;
					left: 36%;
				}

				&:nth-of-type(6) {
					top: 30%;
					left: 12%;
				}

				&:nth-of-type(7) {
					top: 30%;
					left: 48%;
				}

				&:nth-of-type(8) {
					top: 16%;
					left: 62%;
				}

				&:nth-of-type(9) {
					top: 4%;
					left: 66%;
				}

				&:nth-of-type(10) {
					top: 14%;
					left: 50%;
				}

				&:nth-of-type(11) {
					top: 17%;
					left: 77%;
				}

				&:nth-of-type(12) {
					top: 32%;
					left: 80%;
				}
			}

			.light {
				width: 70rpx;
				position: absolute;

				&:nth-last-of-type(1) {
					top: 24%;
					left: 22%;
				}

				&:nth-last-of-type(2) {
					top: 36%;
					left: 33%;
				}

				&:nth-last-of-type(3) {
					top: 32%;
					left: 65%;
				}
			}
		}

		.tree-box {
			position: absolute;
			top: 0;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			justify-content: center;
			pointer-events: none;
			z-index: -1;

			.tree-bg {
				width: 100%;
				height: 100%;
			}
		}

		.bottom-btn {
			position: absolute;
			bottom: 60rpx;
			width: 100%;
			padding: 0 40rpx;
			box-sizing: border-box;

			.btn {
				transition: all .3s;

				&:active {
					opacity: 0.7;
					transform: scale(0.9);
				}
			}
		}

		.top-title {
			padding: 40rpx;

			.btn,
			.tip {
				height: 60rpx;
				border-radius: 30rpx;
				background-color: rgba(255, 255, 255, .8);
				display: flex;
				align-items: center;
				padding: 0 20rpx;
				color: #222;
				font-size: 28rpx;
			}

			.btn {
				transition: all .3s;

				&:active {
					opacity: 0.7;
					transform: scale(0.9);
				}
			}

			.tip {
				width: max-content;
			}
		}

	}
</style>